import { createSlice } from "@reduxjs/toolkit";

//导入登录或注册网络请求模块
import { getUserLoginAPI, getUserInfoAPIcc } from "../../apis/user";

//导入声明变量
import type { AppDispatch } from "../store";
import type { LoginFormItem } from "../../types/login";
import type { userInfo } from "../../types/user";

// 导入token操作
import { setToken, getToken, delToken } from "../../utils/token";

export const userSlice = createSlice({
  name: "user",
  initialState: {
    // 用户token(先从本地获取)
    token: getToken(),
    // 用户信息
    userInfo: {} as userInfo,
  },
  reducers: {
    // 设置用户token
    setUserData(state, action) {
      state.token = action.payload;
      // 将token存入本地
      setToken(action.payload);
    },
    //设置用户信息
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    // 退出登录
    loginOut(state) {
      state.token = "";
      state.userInfo = {};
      delToken();
    },
  },
});

// 登录或注册网络请求
export const getUserAPI = (loginForm: LoginFormItem) => {
  return async (dispatch: AppDispatch) => {
    // 发送登录请求
    const res = await getUserLoginAPI(loginForm);
    dispatch(setUserData(res.data.data.token));
  };
};

// 获取用户信息网络请求
export const getUserInfoAPI = () => {
  return async (dispatch: AppDispatch) => {
    // 发送获取用户信息请求
    const res = await getUserInfoAPIcc();
    dispatch(setUserInfo(res.data.data));
  };
};

// 每个 case reducer 函数会生成对应的 Action creators
export const { setUserData, setUserInfo, loginOut } = userSlice.actions;

export default userSlice.reducer;
